<?php


namespace Huang\PhpPersonalTools;


use Huang\PhpPersonalTools\enum\FeishuEnum;

class FeishuService
{
    protected static $app_id;
    protected static $app_secret;

    /**
     * 初始化配置
     * @param array $config
     */
    public function __construct($config = [])
    {
        $configFile = __DIR__ . '/config.php';
        if (!file_exists($configFile)) {
            throw new \Exception('注意查看当前composer包下的config文件是否存在');
        }
        $configFile = require_once $configFile;
        $configAppId = $configFile['feishu']['app_id'] ?? null;
        $configAPPSECRET = $configFile['feishu']['app_secret'] ?? null;
        self::$app_id = $config['app_id'] ?? ($configAppId ?: null);
        self::$app_secret = $config['app_secret'] ?? ($configAPPSECRET ?: null);
        if (empty(self::$app_id) && empty(self::$app_secret)) {
            throw new \Exception("app_id或app_secrect不能为空");
        }
    }

    /**
     * @description 获取tenant_access_token
     */
    public function tenantAccessToken()
    {

        $redis = RedisService::instance();
        if (empty($redis->get('feishu_tenant_access_token'))) {
            $res = Http::rawSend(FeishuEnum::BASE_URL . FeishuEnum::TENANT_ACESSTOKEN_URL, array('app_id' => self::$app_id, 'app_secret' => self::$app_secret), '', 'post');
            $accesstoken = $res['tenant_access_token'];
            $redis->set('tenant_access_token', $accesstoken, $res['expire']);
        } else {
            $accesstoken = $redis->get('tenant_access_token');
        }
        return $accesstoken;
    }

    /**
     * Notes: 根据飞书id 获取单个用户信息
     * @param $user_id
     * @param $user_id_type (user_id：g7435599 open_id：ou_fb81de63a1597573c8d8e40d71ace319 union_id:on_397bcd63358a129abdcb76b2d6154ded)
     * @return array|mixed
     */
    public function getUserInfoById($user_id, $user_id_type = 'union_id')
    {
        $access_token = $this->tenantAccessToken();
        $res = Http::rawSend(FeishuEnum::BASE_URL . FeishuEnum::SINGLE_USER . "/" . $user_id, array('user_id_type' => $user_id_type), $access_token, 'get');
        return $res['code'] == 0 ? ($res['data']['user'] ?? []) : [];
    }

    /**
     * Notes:获取飞书部门
     * @param $parent
     * @param string $page_token
     * @param array $dataArray
     * @return array
     */
    public function depart($parent, $page_token = '', &$dataArray = [])
    {
        set_time_limit(0);
        try {
            $access_token = $this->tenantAccessToken();
            $res = Http::rawSend(FeishuEnum::BASE_URL . FeishuEnum::DEPARTMENT_URL,
                array('user_id_type' => 'open_id', 'department_id_type' => 'open_department_id', 'parent_department_id' => $parent, 'fetch_child' => 'true', 'page_size' => 10, 'page_token' => $page_token), $access_token, 'get'
            );
            if ($res['code'] == 0) {
                $dataArray = array_merge($dataArray, $res['data']['items']);
                if ($res['data']['has_more'] == true) {
                    $this->depart($parent, $res['data']['page_token'], $dataArray);
                }
            }
            return $dataArray;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());

        }
    }

    /**
     * Notes:获取指定部门下的人员
     * @param $department_id
     * @param string $page_token
     * @param array $dataArray
     * @return array
     */
    public function getUserByDepart($department_id, $page_token = '', &$dataArray = [])
    {
        set_time_limit(0);
        try {
            $access_token = $this->tenantAccessToken();
            $res = Http::rawSend(FeishuEnum::BASE_URL . FeishuEnum::USERS,
                array('user_id_type' => 'open_id', 'department_id_type' => 'open_department_id', 'parent_department_id' => '0', 'fetch_child' => 'false', 'page_size' => 10, 'page_token' => $page_token), $access_token, 'get'
            );
            if ($res['code'] == 0) {
                $dataArray = array_merge($dataArray, $res['data']['items']);
                if ($res['data']['has_more'] == true) {
                    $this->getUserByDepart($department_id, $res['data']['page_token'], $dataArray);
                }
            }
            return $dataArray;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 飞书发送：https://open.feishu.cn/document/ukTMukTMukTM/uYzM3QjL2MzN04iNzcDN/message-card-builder
     * Notes:参考文档  https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/im-v1/message/create_json#45e0953e
     * @param $msg_type  文本消息:text 富文本消息：post 图片消息：image 卡片消息：interactive
     * @param $receive_id
     * @param $con
     * @param string $source 来源
     * @param string $event 事件类型
     * @param string $event 事件类型
     * @param string $content_type 当为模模版时候值为 true
     * @return mixed
     */
    public function send($msg_type, $receive_id, $con, $content_type = false)
    {

        if (empty($receive_id)) {
            return false;
        }
        try {
            $access_token = FeishuService::tenantAccessToken();
            switch ($msg_type) {
                case "image":
                    $content = array(
                        'receive_id' => $receive_id,
                        'msg_type' => $msg_type,
                        'content' => [
                            'image_key' => $con
                        ]
                    );
                    break;
                case "text":
                    $content = [
                        'receive_id' => $receive_id,
                        'content' => "{\"text\":\"$con \\n\"}",
                        'msg_type' => $msg_type
                    ];
                    break;
                case "post":
                    $content = [
                        'receive_id' => $receive_id,
                        'content' => $con,
                        'msg_type' => $msg_type
                    ];
                    break;
                case "interactive":
                    if ($content_type) {
                        /*
                         *  $content = [
                                'type' => 'template',
                                'data' => [
                                    'template_id' => 122,
                                    'template_variable' => []
                                ]
                            ];
                         * */
                        $content = array(
                            'receive_id' => $receive_id,
                            'content' => json_encode($con, 256), //{\"type\": \"template\", \"data\": { \"template_id\": \"ctp_xxxxxxxxxxxx\", \"template_variable\": {\"article_title\": \"这是文章标题内容\"} } }
                            'msg_type' => $msg_type
                        );
                        break;
                    } else {
                        $content = array(
                            'receive_id' => $receive_id,
                            'content' => $con,
                            'msg_type' => $msg_type
                        );
                        break;
                    }

            }
            $sendContent = json_encode($content, 256);
            $res = Http::rawSend(FeishuEnum::RBOOT_SEND_URL,$sendContent,$access_token, 'post');
            if (isset($res['code']) && $res['code'] == 0) { //成功  data 详细的
                return true;
            } else {
                return false;
            }

        } catch (\Exception $e) {
            $record = [
                __CLASS__, __FUNCTION__, $e->getFile(), $e->getLine(), $e->getMessage()
            ];
            return false;
        }
    }


}
